#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include<time.h>
#include "member_manage_types.h"
#include "common.h"

#define MEMBER_INFO_FILE "data/members.dat"  // 数据存储文件名
#define MEMBER_ID_BASE   100001

// 初始化管理员信息
void initAdmin(Admin* admin)
{
	strcpy(admin->username,"admin");
	strcpy(admin->password,"123456");
}


// 管理员登录认证
int adminLongin(Admin* admin,char* user,char* pwd)
{
	return((strcmp(admin->username,user) == 0) && ((strcmp(admin->password,pwd) == 0)));
}


// 会员ID生成
static unsigned int get_new_mid(void)
{
	Member mi;
	unsigned int mid;

	FILE* fp = fopen(MEMBER_INFO_FILE,"rb");
	
	if(fp == NULL)
	{
		return MEMBER_ID_BASE;
	}
	
	fseek(fp,-sizeof(mi),SEEK_END);

	if(fread(&mi,sizeof(mi),1,fp) == 1)
	{
		mid = mid + 1;
	}
	
	else
	{
		mid = MEMBER_ID_BASE;

	}
	
	fclose(fp);
	
	return mid;

}

//验证管理员身份
bool adminAuthentication(void (*success)(void)) 
{
	char user[50], pwd[50];
	Admin admin;

	// 初始化管理员凭证
	initAdmin(&admin);

	// 安全输入账号
	printf("请输入账号：\n");
	if (scanf("%49s", user) != 1) {
		printf("输入错误！\n");
		return false;
	}

	// 安全输入密码
	printf("请输入密码：\n");
	if (scanf("%49s", pwd) != 1) {
		printf("输入错误！\n");
		return false;
	}

	// 验证登录
	if (adminLongin(&admin, user, pwd)) {
		printf("登录成功！\n");
		if (success != NULL) {
			success(); // 执行成功回调函数
		}
		return true;
	}

	printf("登录失败！\n");
	return false;
	
	press_any_key();

}


// 注册会员
void registerMember(void)
{
	Member mi;
	
	printf("请按照下边提示操作\n\n");	
	printf("请输入卡号:\n");
	scanf("%s",mi.card_id);
	printf("请输入您的姓名：\n");
	scanf("%s",mi.name);
	printf("请输入您的性别（1为男，0为女）：\n");
	scanf("%d",(int*)&mi.s);
	printf("请输入您的手机号：\n");
        scanf("%s",mi.number);
	printf("请输入您的生日：\n");
        scanf("%s",mi.birth);

	printf("请输入会员类型（0为次卡，1为月卡，2为年卡）：");
	scanf("%d",(int*)&mi.type);

	if(mi.type == TIMES_PASS)
	{
		printf("请输入次数：");
		scanf("%d",&mi.remainTimes);	
	}
	
		if(mi.type == TIMES_PASS)
	{
		printf("剩余次数：");
		scanf("%d", &mi.remainTimes);
	}

	mi.reg_time = time(NULL);

	if(mi.type == MONTHLY_PASS)
		mi.expire_time = mi.reg_time + 30 * 24 * 60 * 60;
	else
		mi.expire_time = mi.reg_time + 365 * 24 * 60 * 60;

	mi.mid = get_new_mid();
	mi.isActive = 0;

	FILE* fp = fopen(MEMBER_INFO_FILE, "ab");
	
	if(fp == NULL)
	{
		perror("会员注册失败");
		return;
	}

	fwrite(&mi, sizeof(mi), 1, fp);

	fclose(fp);

	printf("\n注册会员成功！\n");
	
	press_any_key();
}


void member_show(void)
{
	Member mi;
	char card_num[11];

	system("clear"); //清屏

	printf("\n会员请刷卡\n");
	scanf("%s",card_num);
	getchar();

	system("clear");

	FILE* fp = fopen(MEMBER_INFO_FILE, "ab");

	if(fp == NULL)
	{
		printf("\n卡片未注册，请联系工作人员处理！\n");
		return;
	}

	while(fread(&mi, sizeof(mi), 1, fp) == 1)
	{
		if(strcmp(mi.card_id, card_num) == 0)
			break;
	}

	if(feof(fp))
	{
		printf("\n卡片未注册，请联系工作人员处理！\n");
	}
	else
	{
		if(mi.isActive == 1)
		{
			printf("\n此卡已注销，请联系工作人员处理！\n");
		}
		else
		{
			printf("\n尊贵的会员，您的个人信息如下：\n\n");
			//print_member_info(&mi);
		}
	}

	fclose(fp);

	system("clear");
}



